<template>
    <Spin :spinning="spinning !== 0">
        <Row justify="space-between" :gutter="[10, 10]">
            <Col>
            <Upload :multiple="true" :show-upload-list="false" :before-upload="handleBeforeUpload"
                class="upload-list-inline">
                <Button type="primary" class="button-gap">
                    <upload-outlined></upload-outlined>
                    上传
                </Button>
            </Upload>
            <Button type="primary" class="button-gap" @click="addVideoDirPost">
                添加视频目录
            </Button>
            </Col>
        </Row>
        <Row>
            <Col>
            <Breadcrumb :style="{ padding: '10px 0px 0px 10px' }">
                <BreadcrumbItem>
                    <a href="#" @click.prevent="jump('')">根目录</a>
                </BreadcrumbItem>
                <BreadcrumbItem v-for="(part, index) in urls" :key="part">
                    <a href="#" @click.prevent="jumpurl(index)">{{ part }}</a>
                </BreadcrumbItem>
            </Breadcrumb>
            </Col>
        </Row>
        <List v-if="filedata && filedata.length > 0" :style="{ padding: '10px 0px 10px 20px' }"
            :grid="{ gutter: 16, xs: 1, sm: 2, md: 4, lg: 4, xl: 6, xxl: 9 }" :data-source="filedata">
            <template #renderItem="{ item }">
                <Dropdown :trigger="['contextmenu']">
                    <ListItem>
                        <a v-on:click="jump(item.keypath)">
                            <Tag v-text="item.name" color="blue" class="mb-2"></Tag>
                        </a>
                    </ListItem>
                    <template #overlay>
                        <Menu>
                            <MenuItem key="1" @click="clickVideoDir(item)">修改</MenuItem>
                            <Popconfirm title="确定删除?" ok-text="确定" cancel-text="取消" @confirm="delVideoDirPost(item)">
                                <MenuItem key="2">删除</MenuItem>
                            </Popconfirm>
                        </Menu>
                    </template>
                </Dropdown>
            </template>
        </List>
        <List :grid="{ gutter: 16, column: 4 }" :data-source="data">
            <template #renderItem="{ item }">
                <ListItem>
                    <vue3VideoPlay :src=item.path width="370px" height="200px" />
                    <Dropdown :trigger="['contextmenu']">
                        <Tag>{{ item.name }}</Tag>
                        <template #overlay>
                            <Menu>
                                <MenuItem key="1" @click="clickVideoName(item)">修改</MenuItem>
                                <Popconfirm title="确定删除?" ok-text="确定" cancel-text="取消" @confirm="delVideoPost(item)">
                                    <MenuItem key="2">删除</MenuItem>
                                </Popconfirm>
                            </Menu>
                        </template>
                    </Dropdown>
                    <Tag>{{ getSize(item.length) }}</Tag>
                    <Tag>{{ item.utime }}</Tag>
                </ListItem>
            </template>
        </List>
        <Pagination :style="{ float: 'right' }" v-model:current="params.currentPage" v-model:page-size="params.pageSize"
            :total="total" @change="onChange">
        </Pagination>
    </Spin>
    <Modal @ok="submitVideoDir(true)" @cancel="submitVideoDir(false)" :title="imgdirTitle" v-model:open="openimgdir">
        <Form>
            <FormItem label="视频类型名称">
                <Input v-model:value="params.name" />
            </FormItem>
        </Form>
    </Modal>
    <Modal @ok="submitVideo(true)" @cancel="submitVideo(false)" :title="imgTitle" v-model:open="openimg">
        <Form>
            <FormItem label="视频名称">
                <Input v-model:value="params.name" />
            </FormItem>
        </Form>
    </Modal>
</template>
<script setup lang="ts">
import { Api } from "../util/Api";
import { upload, get, post } from "../util/MyAxios";
import { showMessage } from "../util/Mes";
import {
    Row,
    Col,
    List,
    ListItem,
    Tag,
    Button,
    Breadcrumb,
    BreadcrumbItem,
    Upload,
    message,
    Dropdown,
    MenuItem,
    Menu,
    Modal,
    Form,
    FormItem,
    Input,
    Popconfirm,
    Pagination,
    Spin,
} from "ant-design-vue";
import {
    UploadOutlined,
} from "@ant-design/icons-vue";
import { ref, onBeforeMount } from "vue";

interface FileItem {
    index: number;
    path: string;
    name: string;
    keypath: string;
    isfolder: boolean;
    ctime: Date;
    utime: Date;
    isimg: boolean;
    width: number;
    height: number;
    length: number;
    src: string;
    thumbnail: string;
}
// 请求api时附带参数
const params = ref({
    path: "",
    name: "",
    oldname: "",
    newname: "",
    currentPage: 1,
    pageSize: 8,
});

const spinning = ref<number>(0);
const filename = ref("");
const filedata = ref<FileItem[]>([]);
const imgdata = ref<FileItem[]>([]);
const data = ref<FileItem[]>([]);
const urls = ref<string[]>([]);

const uploadpath = ref("");
const openimgdir = ref<boolean>(false);
const openimg = ref<boolean>(false);
const imgdirTitle = ref("");
const imgTitle = ref("");

const total = ref(50);

//分页切换页面
function onChange() {
    fetchData();
}

//文件大小格式转换
function getSize(length) {
    if (length === 0) return "0 B";

    const units = ["B", "KB", "MB", "GB", "TB"];
    let index = Math.floor(Math.log(length) / Math.log(1024));
    if (index > units.length - 1) index = units.length - 1;

    const convertedSize = length / Math.pow(1024, index);
    return convertedSize.toFixed(2) + " " + units[index];
}

const handleBeforeUpload = (file) => {
    spinning.value++;
    const formData = new FormData();
    formData.append("file", file);
    if (params.value.path) {
        formData.append("fileurl", params.value.path);
    }
    return upload(Api.Video_UploadVideo, formData, {
        headers: {
            "Content-Type": "multipart/form-data",
        },
    })
        .then((response) => {
            spinning.value--;
            message.info("已上传:" + response.data);
            fetchData();
            return false;
        })
        .catch((error) => {
            console.error(error);
            return false;
        });
};

onBeforeMount(() => {
    fetchData();
});

async function fetchData() {
    await get(Api.Video_GetVideoPathInfo, params.value)
        .then((response) => {
            // console.log(response.data);
            if (response.data != null && response.data.rows != null) {
                filedata.value = response.data.rows.filter((re) => re.isfolder);
                imgdata.value = response.data.rows.filter((re) => !re.isfolder);
            }
            data.value = imgdata.value;
            total.value = response.data.total;
        })
        .catch((error) => {
            console.error("Error fetching data:", error);
            message.info(error.name + error.message + error.stack);
        });
}

function jump(url) {
    params.value.path = url;
    uploadpath.value = url;
    filename.value = url;
    if (url && url.length > 0) {
        urls.value = params.value.path.split("/");
    } else {
        urls.value = [];
    }
    fetchData();
}

//回到指定目录
function jumpurl(index) {
    let urlstr = "";
    let t = urls.value.length - 1 - index;
    if (t > 0) {
        for (let i = 0; i < t; i++) {
            urls.value.pop();
        }
    }
    for (let i = 0; i < urls.value.length; i++) {
        if (i <= index) {
            if (urlstr === "") {
                urlstr = urls.value[i];
            } else {
                urlstr = urlstr + "/" + urls.value[i];
            }
        }
    }
    params.value.path = urlstr;
    filename.value = urlstr;
    uploadpath.value = urlstr;
    fetchData();
}

function submitVideoDir(b) {
    if (b) {
        params.value.newname = params.value.name;
        console.log(params.value);
        editVideoDirNamePost();
    }
    openimgdir.value = false;
    fetchData();
}
function submitVideo(b) {
    if (b) {
        params.value.newname = params.value.name;
        console.log(params.value);
        editVideoNamePost();
    }
    openimg.value = false;
    fetchData();
}
//删除一个视频
async function delVideoPost(item) {
    params.value.name = item.name;
    await post(Api.Video_DelVideo, params.value)
        .then((response) => {
            showMessage(response.data, "删除视频");
            fetchData();
        })
        .catch((error) => {
            console.error(error);
        });
}
function clickVideoDir(item) {
    params.value.name = item.name;
    params.value.oldname = item.name;
    imgdirTitle.value = "修改视频目录";
    openimgdir.value = true;
}

//编辑视频名称
function clickVideoName(item) {
    params.value.name = item.name;
    params.value.oldname = item.name;
    imgTitle.value = "修改视频名称";
    openimg.value = true;
}
//删除一个视频目录
async function delVideoDirPost(item) {
    params.value.name = item.name;
    await post(Api.Video_DelVideoDir, params.value)
        .then((response) => {
            showMessage(response.data, "删除视频目录");
            fetchData();
        })
        .catch((error) => {
            console.error(error);
        });
}
//创建一个视频目录
async function addVideoDirPost() {
    await post(Api.Video_AddVideoDirectory, params.value)
        .then((response) => {
            showMessage(response.data !== "", "添加目录");
            if (response.data !== "") {
                urls.value.push(response.data);
                jumpurl(urls.value.length - 1);
            }
        })
        .catch((error) => {
            console.error(error);
        });
}
//修改视频目录名称
async function editVideoDirNamePost() {
    await post(Api.Video_EditVideoDirOrName, params.value)
        .then((response) => {
            showMessage(response.data, "修改目录名称");
            fetchData();
        })
        .catch((error) => {
            console.error(error);
        });
}

//修改视频名称
async function editVideoNamePost() {
    await post(Api.Video_EditVideoDirOrName, params.value)
        .then((response) => {
            showMessage(response.data, "修改名称");
            fetchData();
        })
        .catch((error) => {
            console.error(error);
        });
}

// const options = reactive({
//     width: "800px", //播放器宽度
//     height: "450px", //播放器高度
//     color: "#409eff", //主题色
//     title: "", //视频名称
//     src: "http://localhost:8848/Video/1.mp4", //视频源
//     muted: false, //静音
//     webFullScreen: false,
//     speedRate: ["0.75", "1.0", "1.25", "1.5", "2.0"], //播放倍速
//     autoPlay: false, //自动播放
//     loop: false, //循环播放
//     mirror: false, //镜像画面
//     ligthOff: false, //关灯模式
//     volume: 0.3, //默认音量大小
//     control: true, //是否显示控制
//     controlBtns: [
//         "audioTrack",
//         "quality",
//         "speedRate",
//         "volume",
//         "setting",
//         "pip",
//         "pageFullScreen",
//         "fullScreen",
//     ], //显示所有按钮,
// });
</script>

<style scoped>
.button-gap {
    margin-left: 10px;
}
</style>